#include "tablemodel.h"

TableModel::TableModel(QObject *parent)
    : QAbstractTableModel{parent}
{

}

int TableModel::rowCount(const QModelIndex &parent) const
{
    return m_datas.size();
}

int TableModel::columnCount(const QModelIndex &parent) const
{
     return m_header.size();
}

QVariant TableModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();
    if (role == Qt::DisplayRole)
    {
        int col = index.column();
        int row = index.row();
        QString field = m_header[col];
        return m_datas[row][field];
    }
    return QVariant();
}

QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role == Qt::DisplayRole && orientation == Qt::Horizontal && section < m_header.size())
        return m_header[section];
    return QAbstractTableModel::headerData(section, orientation, role);
}

bool TableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if(!index.isValid())
        return false;
    if(role == Qt::DisplayRole || role == Qt::EditRole)
    {
        int col = index.column();
        int row = index.row();
        QString field = m_header[col];
        m_datas[row][field] = value;
        return true;
    }
    return false;
}

void TableModel::setModelDatas(const VMSV &datas)
{
    // 修改表中数据源
    m_datas.clear();
    m_datas = datas;

    // 开始更新数据
    beginResetModel();
    endResetModel();
}
